package com.coldwindblows.blog.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * zip压缩工具类
 * @author Administrator
 *
 */
public class ZipUtils {

	public static void zipFoler(String srcFolder, String destZipFile) throws Exception {
		FileOutputStream fileWriter = new FileOutputStream(destZipFile);
		ZipOutputStream zip = new ZipOutputStream(fileWriter);
		
		addFolderToZip("", srcFolder, zip);
		zip.flush();
		zip.closeEntry();
		zip.close();
	}
	
	public static void zipFile(String filePath, String zipPath) throws Exception {
		byte[] buffer = new byte[1024];
		FileOutputStream fos = new FileOutputStream(zipPath);
		ZipOutputStream zos = new ZipOutputStream(fos);
		ZipEntry ze = new ZipEntry("spy.log");
		zos.putNextEntry(ze);
		FileInputStream in = new FileInputStream(filePath);
		int len;
		while((len = in.read(buffer)) > 0) {
			zos.write(buffer, 0, len);
		}
		in.close();
		zos.closeEntry();
		zos.close();
	}
	
	private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception {
		File folder = new File(srcFile);
		if(folder.isDirectory()) {
			addFolderToZip(path, srcFile, zip);
		} else {
			byte[] buf = new byte[1024];
			int len;
			FileInputStream in = new FileInputStream(srcFile);
			zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
			while((len = in.read(buf)) > 0) {
				zip.write(buf, 0, len);
			}
			in.close();
		}
	}

	private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
		File folder = new File(srcFolder);
		if(null != path && folder.isDirectory()) {
			String[] fileList = folder.list();
			if(fileList != null) {
				for(String fileName : fileList) {
					if(path.equals("")) {
						addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
					} else {
						addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
					}
				}
			}
		}
	}
}
